package com.fingard.dsp.bank.directbank.gdb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directConfig.TaskTimerSet;
import com.fingard.dsp.bank.directbank.bankInterface.IScheduleTask;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.DelayCounter;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.FGBiz;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description TODO
 **/
public class GDB01ScheduleTask extends GDB01Base implements IScheduleTask {
    private String logCode = "GDB01"+ File.separator+"TaskReceiptPro";
    private TaskTimerSet timer;
    private ReceiptProConfig proConfig;
    //private boolean byLocalhost;

    private static DelayCounter delayCounter = new DelayCounter(45, 2);//最大延时45分钟，按平方计算，即4次=4*4=16分钟
    public static void resetDelayCounter(){
        delayCounter.resetZeroCount();
    }
    @Override
    public void execTask(TaskTimerSet timerSet) {
        try{
            if (timerSet.taskNameList.toLowerCase().contains("downreceiptpro")) {

                timer = timerSet;
                proConfig = ReceiptPro.getReceiptProConfig();
                //T+1推送
                String beginDate = timerSet.taskParams.get("begindaycount");
                String endDate = timerSet.taskParams.get("enddaycount");
                downlaodForSftpAndInsert(beginDate, endDate);
            }
        }catch (Exception e){
            FGBiz.logTrace.exception(logCode, e);
        }
    }
    /**
     * sftp方式回单获取
     *
     * @return
     */
    public void downlaodForSftpAndInsert(String beginDate, String endDate) throws IOException {

        SftpPortClient sftpPortClient = null;
        String saveDirPathTemp = proConfig.localSaveMainDir;
        //String qryDay8 = Format.Date8Format.format(new Date());
        try {
            String qryBeginDay = getDate8(beginDate);
            String qryEndDay8 = getDate8(endDate);
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(Format.Date8Format.parse(qryBeginDay));

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(Format.Date8Format.parse(qryEndDay8));
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                String qryDay8 = Format.Date8Format.format(tmpCalendarFrom.getTime());
                FtpSet ftpSet = bankFront.getFtpSet("receipt");
                ftpSet.downDir = StringHelper.trimEnd(ftpSet.downDir, "/") + "/";
                WriteBankLogLn("SFTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始遍历服务器文件目录" + ftpSet.downDir + qryDay8);

                sftpPortClient = new SftpPortClient(ftpSet);

                ArrayList<String> ftpFileList = sftpPortClient.listNames(ftpSet.downDir + qryDay8);
                if (ftpFileList.size() == 1) {
                    WriteBankLogLn("当前日期：" + qryDay8 + "无回单文件");
                    return;
                }
                WriteBankLogLn("下载到本地目录为：" + saveDirPathTemp);
                System.out.println(ftpFileList);

                WriteBankLogLn("sftp目录下文件名为：" + Arrays.toString(ftpFileList.toArray()));

                for (String file : ftpFileList) {
                    FtpReceiver ftpReceiver = sftpPortClient.downloadFileByName(qryDay8, saveDirPathTemp, file);
                    if (ftpReceiver.isCompleted) {
                        WriteBankLogLn("下载成功，下载路径为：" + saveDirPathTemp + "文件名为" + file);
                    }
                }
                File tmpFile = new File(saveDirPathTemp);
                File[] files = tmpFile.listFiles();
                int[] retVals = new int[3];
                retVals[0] = 0;//总pdf个数
                retVals[1] = 0;//新增
                retVals[2] = 0;//已存在
                for (File file : files) {
                    String ftpFileName = file.getName();
                    if (ftpFileName.contains(".txt")) {
                        WriteBankLogLn("解析汇总文件:" + ftpFileName);
                        //保存路径

                        //解析汇总文件返回map
                        String[] line = FileHelper.readFileText(saveDirPathTemp + File.separator + ftpFileName, "UTF-8").split("\n");
                        int totalFiles = 0;
                        //读取文件内容
                        Pattern p = Pattern.compile("\t|\r|\n");

                        for (String pfiles : line) {

                            if (!pfiles.contains("|")) {
                                //第一行不处理
                            } else {
                                //入库
                                String[] receiptInfo = pfiles.split("\\|");
                                String secAccont = receiptInfo[receiptInfo.length - 1];
                                Matcher m = p.matcher(secAccont);
                                secAccont = m.replaceAll("");
                                ReceiptData eachData = new ReceiptData();
                                /**回单唯一标识（在银行端的唯一标识（该账号的唯一），如招行的打印实例号）*/
                                eachData.istNbr = receiptInfo[1];
                                /**回单关联号（回单编号）*/
                                eachData.receiptNo = receiptInfo[1];
                                /**业务参考号*/
                                eachData.busRef = receiptInfo[1];
                                eachData.amount = new BigDecimal(0.00);
                                eachData.bank = "307";
                                eachData.srcSys = "GDB01";
                                if (receiptInfo[4].contains("D")) {
                                    eachData.moneyWay = "1";
                                } else if (receiptInfo[4].contains("C")) {
                                    eachData.moneyWay = "2";
                                }
                                /**回单文件--本地文件相对路径*/
                                String sourcePath = saveDirPathTemp + File.separator + receiptInfo[1] + ".pdf";
                                eachData.localFile = StringHelper.getRelativePath(sourcePath, saveDirPathTemp);
                                /**回单文件类型*/
                                eachData.fileType = "1";
                                eachData.cur = "1";
                                eachData.srcFile = sourcePath;
                                eachData.downState = "2";
                                eachData.downTime = new Date();
                                eachData.receiptNo = receiptInfo[1];
                                eachData.busRef = receiptInfo[1] + receiptInfo[0] + qryDay8;
                                eachData.oppActNum = secAccont.length() == 0 ? null : secAccont;
                                eachData.ownAct = receiptInfo[0];
                                eachData.busDate = Integer.valueOf(qryDay8);
                                eachData.downInfo = "下载成功";
                                /**上传状态：指文件从银行端下载完成后，上传至ftp或ats或oss或客制化文件服务的状态，1未上传；2已上传；3上传失败；4上传中*/
                                eachData.upState = "1";
                                /**推送状态：指文件上传完成后，回单数据推送至ats或客制化平台的状态，1未推送；2已推送；3推送失败；4推送中*/
                                eachData.pushState = "1";
                                /**创建时间*/
                                eachData.createdOn = new Date();
                                /**最后修改时间*/
                                eachData.lastModifiedOn = new Date();
                                /**版本号*/
                                eachData.rowVersion = 1;
                                ReceiptDataHelper receiptHelper = new ReceiptDataHelper(reqHeader.tenant, eachData.getBusDate());
                                int inRe = receiptHelper.insertIfNotExist(eachData, true);
                                if (inRe > 0) {
                                    retVals[1] = retVals[1] + 1;
                                } else if (inRe == 0) {
                                    retVals[2] = retVals[2] + 1;
                                }
                                WriteBankLogLn(eachData.receiptNo + "写入数据库，影响行数：" + inRe);
                            }
                        }

                    }
                }
                tmpCalendarFrom = tmpClndrStepTo;
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            WriteBankLogLn(ex);
        } finally {
            if (sftpPortClient != null) {
                sftpPortClient.disconnect();
            }
        }

    }
    public String getDate8(String beginDays) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyyMMdd");
        Date beginDate = new Date();
        Calendar date = Calendar.getInstance();
        date.setTime(beginDate);
        if (beginDays != null && beginDays.contains("-")) {
            int days = Integer.valueOf(beginDays.replace("-", ""));
            date.set(Calendar.DATE, date.get(Calendar.DATE) - days);
        }
        return dft.format(date.getTime());
    }

}
